package main

import (
	"errors"
	"fmt"
	"io"
	"net"
	"time"
)

func ReadDt(conn net.Conn) []byte {
	res, _ := ReadDtEx((conn))
	return res
}

func ReadDtEx(conn net.Conn) ([]byte, error) {
	if conn == nil {
		return nil, errors.New("conn is nil")
	}
	var size = 8196
	var buf []byte

	for {
		tmp := make([]byte, size)
		conn.SetReadDeadline(time.Now().Add(1 * time.Second))
		//fmt.Println("-----------------------1", size)
		n, err := conn.Read(tmp)
		if err == io.EOF {
			return buf, err
		}
		//fmt.Println("-----------------------2", size)
		if buf == nil {
			buf = tmp[:n]
		} else {
			buf = append(buf, tmp[:n]...)
		}
		if n < size || err != nil {
			//return buf, err
			break
		}
		size = size * 2
	}
	return buf, nil

}

func WriteDt(dt []byte, conn net.Conn) error {
	if conn == nil {
		return errors.New("connetion is nil")
	}
	n, err := conn.Write(dt)
	//fmt.Println("-----------", string(dt))
	if err != nil {
		fmt.Println("write err:", err)
	} else if n == 0 {
		fmt.Println("n:", err)
	} else {
		conn.Write([]byte("\r\n"))
	}
	return err
}
